package com.runen.wnhz.runen.ui.activity.main;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.runen.wnhz.runen.R;
import com.runen.wnhz.runen.bean.CanDownloadLessonBean;
import com.runen.wnhz.runen.bean.CheckBoxAllDownloadBean;
import com.runen.wnhz.runen.bean.SubmitDownloadBean;
import com.runen.wnhz.runen.bean.WantLearnBean;
import com.runen.wnhz.runen.common.utils.ACacheUtlis;
import com.runen.wnhz.runen.common.utils.FileUtils;
import com.runen.wnhz.runen.common.utils.NetUtils;
import com.runen.wnhz.runen.common.utils.OkHttpUtils;
import com.runen.wnhz.runen.common.utils.StatusBarCompatUtils;
import com.runen.wnhz.runen.common.utils.ToastUtil;
import com.runen.wnhz.runen.data.entity.UserBean;
import com.runen.wnhz.runen.di.component.ApplicationComponent;
import com.runen.wnhz.runen.ui.activity.BaseActivity;
import com.runen.wnhz.runen.ui.activity.login.LoginForPersonalActivity;
import com.runen.wnhz.runen.ui.adapter.puadapter.CanDownloadLessonAdapter;
import com.runen.wnhz.runen.widget.TitleBuilder;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DownloadActivity extends BaseActivity {

    @BindView(R.id.list_canDownloadLesson)
    ListView listCanDownloadLesson;
    @BindView(R.id.text_atOnceDownload)
    TextView textAtOnceDownload;
    @BindView(R.id.image_checked)
    ImageView imageChecked;
    @BindView(R.id.text_check)
    TextView textCheck;
    private String token;

    private String lid;

    private int totalSmallSelection = 0;

    public static int totalCheckNum = 0;

    public static boolean isFromAdapterCheckAll = false;

    public static List<SubmitDownloadBean> videoUrl;

    private BroadcastReceiver broadcastReceiver;
    private long videoDownloadId;

    private boolean isFirstClick = true;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_download;
    }

    @Override
    protected void onTitleClickListen(TitleBuilder.TitleButton clicked) {
        switch (clicked) {
            case LEFT:
                finish();
                break;
            case MIDDLE:
                break;
            case RIGHT:
                break;
            default:
                break;
        }
    }

    private void getCanDownloadLessonList() {
        if (token != null && lid != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("lid", lid).build();
            Request request = new Request.Builder().url(NetUtils.CAN_DOWNLOAD_LESSON).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("数据请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleCanDownloadLessonData(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("数据请求出现异常");
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleCanDownloadLessonData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            final String json = responseBody.string();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CanDownloadLessonBean canDownloadLessonBean = new Gson().fromJson(json, CanDownloadLessonBean.class);
                    if ("1".equals(canDownloadLessonBean.getRe())) {
                        List<CanDownloadLessonBean.DataBean> dataBeans = canDownloadLessonBean.getData();
                        if (dataBeans != null) {
                            for (int i = 0; i < dataBeans.size(); i++) {
                                CanDownloadLessonBean.DataBean dataBean = dataBeans.get(i);
                                totalSmallSelection = totalSmallSelection + dataBean.getNext_list().size();
                            }
                            listCanDownloadLesson.setAdapter(new CanDownloadLessonAdapter(DownloadActivity.this, dataBeans, totalSmallSelection));
                        }
                    } else if ("0".equals(canDownloadLessonBean.getRe())) {
                        ToastUtil.showToast(canDownloadLessonBean.getInfo());
                    } else if ("-1".equals(canDownloadLessonBean.getRe())) {
                        ToastUtil.showToast(canDownloadLessonBean.getInfo());
                        startActivity(new Intent(DownloadActivity.this, LoginForPersonalActivity.class));
                    }
                }
            });
        }
    }

    @Override
    protected void initStart() {
        StatusBarCompatUtils.getInstance().TranslucentStatusBar(this, R.color.title_green);
        ACacheUtlis cacheUtlis = ACacheUtlis.getInstance();
        if (cacheUtlis != null) {
            UserBean reqeustUser = cacheUtlis.getReqeustUser(this);
            if (reqeustUser != null) {
                token = reqeustUser.getToken();
            }
        }
        lid = getIntent().getStringExtra("lid");
        videoUrl = new ArrayList<>();
        getCanDownloadLessonList();
        // 注册广播监听系统的下载完成事件。
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (ID == DownloadActivity.this.videoDownloadId) {
                    Toast.makeText(getApplicationContext(), "一个视频下载完成，已保存至" + FileUtils.createFileCatalogue() + "目录下", Toast.LENGTH_LONG).show();
                }
                dismissDialog();
                for (SubmitDownloadBean submit : videoUrl) {
                    if (submit.getTag() == ID) {
                        submitDownloadSuccessLesson(submit);
                    }
                }
            }
        };
        registerReceiver(broadcastReceiver, intentFilter);
    }

    private void submitDownloadSuccessLesson(SubmitDownloadBean submitDownloadBean) {
        String titleId = submitDownloadBean.getTitleId();
        String nid = submitDownloadBean.getNid();
        if (token != null && lid != null && titleId != null && nid != null) {
            FormBody formBody = new FormBody.Builder().add("token", token).add("lid", lid).add("title_id", titleId).add("nid", nid).build();
            Request request = new Request.Builder().url(NetUtils.DOWNLOAD_SUCCESS_SUBMIT).post(formBody).build();
            Call newCall = OkHttpUtils.getOkHttpClient().newCall(request);
            newCall.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast("下载视频成功提交服务器失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        handleSubmitDownloadData(response);
                    } catch (IOException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.showToast("下载视频成功提交服务器出现异常");
                            }
                        });
                    }
                }
            });
        }
    }

    private void handleSubmitDownloadData(Response response) throws IOException {
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                final String json = responseBody.string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        WantLearnBean wantLearnBean = new Gson().fromJson(json, WantLearnBean.class);
                        if ("1".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                        } else if ("0".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                        } else if ("-1".equals(wantLearnBean.getRe())) {
                            ToastUtil.showToast(wantLearnBean.getInfo());
                            startActivity(new Intent(DownloadActivity.this, LoginForPersonalActivity.class));
                        }
                    }
                });
            }
        }
    }

    @Override
    public void initToolBar(TitleBuilder mTitleBuilder) {
        mTitleBuilder.setMiddleTitleText("下载")
                .setLeftDrawable(R.mipmap.icon_back)
                .seTitleBgRes(R.mipmap.bg_title)
                .setMiddleTitleTextColor(ContextCompat.getColor(this, R.color.text_white));
    }

    @Override
    public void setupAcitivtyComponent(ApplicationComponent appComponent) {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
    }

    @OnClick({R.id.text_atOnceDownload,R.id.linear_checked})
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.text_atOnceDownload:
                System.out.println("videoUrl == " + videoUrl.toString());
                downloadVideoToNative();
                break;
            case R.id.linear_checked:
                CheckBoxAllDownloadBean checkBoxAllDownloadBean = new CheckBoxAllDownloadBean();
                if(isFirstClick){
                    checkBoxAllDownloadBean.setAllChecked(true);
                    Glide.with(this).load(R.mipmap.icon_rb_sele).into(imageChecked);
                    isFirstClick = false;
                }else{
                    Glide.with(this).load(R.mipmap.icon_rb_unsele).into(imageChecked);
                    checkBoxAllDownloadBean.setAllChecked(false);
                    isFirstClick = true;
                }
                checkBoxAllDownloadBean.setFromAdapter(false);
                EventBus.getDefault().post(checkBoxAllDownloadBean);
                break;
        }
    }

    private void downloadVideoToNative() {
        if (videoUrl != null) {
            if (videoUrl.size() > 0) {
                progressDialog.setMessage("正在下载中，下载进度去打开通知栏查看");
                showProgressDialog();
                //获取下载管理器
                DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                for (SubmitDownloadBean submitDownloadBean : videoUrl) {
                    String url = submitDownloadBean.getVideoUrl();
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    //指定下载路径和下载文件名
                    request.setDestinationInExternalPublicDir(FileUtils.createFileCatalogue(), url);
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    //将下载任务加入下载队列，否则不会进行下载
                    videoDownloadId = downloadManager.enqueue(request);
                    submitDownloadBean.setTag(videoDownloadId);
                }

            } else {
                ToastUtil.showToast("暂无可下载视频");
            }
        }
    }

    @Subscriber
    public void onReceiveCheckBoxAllDownloadBeanEvent(CheckBoxAllDownloadBean checkBoxAllDownloadBean) {
        if (checkBoxAllDownloadBean != null) {
            if(checkBoxAllDownloadBean.isFromAdapter()) {
                if (checkBoxAllDownloadBean.isAllChecked()) {
                    Glide.with(this).load(R.mipmap.icon_rb_sele).into(imageChecked);
                    isFirstClick = false;
                } else {
                    Glide.with(this).load(R.mipmap.icon_rb_unsele).into(imageChecked);
                    isFirstClick = true;
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        isFromAdapterCheckAll = false;
        totalCheckNum = 0;
        videoUrl.clear();
        videoUrl = null;
        unregisterReceiver(broadcastReceiver);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

}
